import os;
import os.path;
import exiftool;
import xmp;
import re;

exiftool_read = os.path.join(os.path.dirname(__file__),'exiftool.pl');

def read(file):
    stdin,stdout = os.popen2(['perl',exiftool_read,file]);
    tags = [];
    try:
        for line in stdout.readlines():
            splittedLine = line.split(':',1);
            keys = splittedLine[0];
            if len(splittedLine) > 1:
                value = splittedLine[1];
            else:
                value = None;
            splittedKeys = keys.split(',',4);
            if len(splittedKeys) == 5:
                (group0,group1,category,id,tag) = splittedKeys;
                tags.append({'group0': group0,'group1': group1,'category': category,'id' : id,'tag': tag,'value': value.strip()});
    finally:
        stdout.close();
    return tags;
    
def readXmpTags(file):
    exiftoolTags = read(file);
    xmpTags = {};
    for tag in exiftoolTags:
        if tag['group1'].startswith('XMP-'):
            prefix = tag['group1'][4:];
            xmpTag = xmp.getProperty(tag['id'],prefix);
            if xmpTag != None:
                if xmpTags.has_key(xmpTag.getPrefixedName()):
                    oldValue = xmpTags[xmpTag.getPrefixedName()];
                else:
                    oldValue = None;
                xmpTags[xmpTag.getPrefixedName()] = parse(xmpTag.typedecl,tag['value'],oldValue);
    return xmpTags;

def parse(type,text,value):
    if type.isSequence():
        if value == None:
            value = [];
        value.append(parse(type.elementsType,text,None));
    elif type.isBag():
        if value == None:
            value = [];
        value.append(parse(type.elementsType,text,None));
    elif type.isAlternative():
        if value == None:
            value = {};
        value['default'] = parse(type.elementsType,text,None);
    elif type.isStructure():
        pass;
    elif isinstance(type,xmp.Date):
        value = parseDate(text);
    else:
        value = type.parse(text);
    return value;

dateParser = re.compile('^(?P<year>\d\d\d\d)(?::(?P<month>\d\d)(?::(?P<day>\d\d)(?: (?P<hour>\d\d):(?P<minute>\d\d)(?::(?P<second>\d\d))?)?)?)?$');

def parseDate(text):
    if len(text) == 0:
        return None;
    matcher = dateParser.match(text);        

    if matcher == None:
        return None;
    year = intOrNone(matcher.group('year'));
    month = intOrNone(matcher.group('month'));
    day = intOrNone(matcher.group('day'));
    hour = intOrNone(matcher.group('hour'));
    minute = intOrNone(matcher.group('minute'));
    second = intOrNone(matcher.group('second'));
#        timeZoneZ = matcher.group('Z') != None;
#        timeZoneSign = matcher.group('tzs');
#        timeZoneHour = intOrNone(matcher.group('tzh'));
#        timeZoneMinute = intOrNone(matcher.group('tzm'));
    
    return (year,month,day,hour,minute,second);
        
    

if __name__ == '__main__':
    print readXmpTags('/home/giorgio/Pictures/2006/200607/20060707/DSCF2247.JPG');
                                                 